package com.ql.service.serviceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ql.dao.IUserDao;
import com.ql.dao.MenuDao;
import com.ql.dao.ProjectDao;
import com.ql.dao.SectionDao;
import com.ql.domain.*;
import com.ql.domain.response.JsonResult;
import com.ql.domain.response.MenuNode;
import com.ql.domain.response.OperatorDetails;
import com.ql.service.IUserService;
import com.ql.utils.BCryptPasswordEncoderUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class IUserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private SectionDao sectionDao;
    @Autowired
    private ProjectDao projectDao;
/*    @Autowired
    private HttpServletRequest request;*/

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        try {
            userInfo = userDao.findByUsername(username);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用自定义对象继承User对象扩展需要的属性
        OperatorDetails user = new OperatorDetails(userInfo.getUsername(), userInfo.getPassword(), userInfo.getState() == 0 ? true : false, true, true, true, getAuthority(userInfo));
        user.setId(userInfo.getId().toString());
        user.setName(userInfo.getName());
        user.setTel(userInfo.getTel());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            //由于前端需要用jquery处理 ,转为json处理
            String s = objectMapper.writeValueAsString(userInfo.getMenus());
            user.setMenus(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        /*  user.setSections(userInfo.getSections());*/
//        user.setSelectTemplates(userInfo.getSelectTemplates());
        return user;
    }

    private List<SimpleGrantedAuthority> getAuthority(UserInfo userInfo) {
        List<Permission> permissions = userInfo.getPermissions();
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (Permission permission : permissions) {
            list.add(new SimpleGrantedAuthority("ROLE_" + permission.getRoleName()));
        }
        return list;
    }


    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public JsonResult findAll(String name, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<UserInfo> infoList = userDao.findAll(name);
        PageInfo pageInfo = new PageInfo(infoList);
        return JsonResult.success(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 保存用户
     *
     * @param userInfo
     * @return
     */
    @Override
    public JsonResult save(UserInfo userInfo) {

        try {
            //将用户传入的密码加密
            userInfo.setPassword(BCryptPasswordEncoderUtils.encodePassword(userInfo.getPassword()));
            //保存用户
            int i = userDao.save(userInfo);
            if (i < 1) {
                return JsonResult.error("保存用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("保存用户失败,请重试");
        }

        /*//添加初始父菜单
        List<Integer> prentId = menuDao.findPrentId();
        for (Integer menuId : prentId) {
            userDao.saveInitMenu(userInfo.getId(), menuId);
        }*/
        try {
            //获得保存用户的主键id
            Integer userId = userInfo.getId();
            //根据主键id关联初始权限
            Integer userLevel = userInfo.getUserLevel();
            if (StringUtils.isNotEmpty(userLevel.toString()) && StringUtils.isNotEmpty(userId.toString())) {
                if (userLevel == 1) {
                    int sicu = userDao.saveInitUser(userId, 1);
                    if (sicu < 1) {
                        return JsonResult.error("用户关联初始权限失败,请重试");
                    }
                } else if (userLevel == 2) {
                    int siau = userDao.saveInitUser(userId, 2);
                    if (siau < 1) {
                        return JsonResult.error("用户关联初始权限失败,请重试");
                    }
                } else if (userLevel == 3) {
                    int sup = userDao.saveInitUser(userId, 3);
                    if (sup < 1) {
                        return JsonResult.error("用户关联初始权限失败,请重试");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("用户关联初始权限失败,请重试");
        }

        return JsonResult.success("添加成功");
    }

    /**
     * 修改用户
     *
     * @param userInfo
     * @return
     */
    @Override
    public JsonResult update(UserInfo userInfo) {
        if (StringUtils.isNotEmpty(userInfo.getPassword())) {
            userInfo.setPassword(BCryptPasswordEncoderUtils.encodePassword(userInfo.getPassword()));
        }
        try {
            userDao.update(userInfo);
            userDao.updateUserLevel(userInfo.getUserLevel(), userInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
        return JsonResult.success("修改成功");
    }

    /**
     * 删除指定用户
     *
     * @param id
     * @return
     */
    @Override
    public JsonResult del(Integer id) {
        try {
            //根据id删除用户关联的标段


      /*      //根据id删除用户的权限
            userDao.delPermissionByUserId(id);
            //根据id删除用户的导航权限
            userDao.delMenuByUserId(id);*/
            //根据id删除用户
            userDao.delUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
        return JsonResult.success();
    }

    /**
     * 根据id获取菜单权限列表
     *
     * @param id
     * @return
     */
    @Override
    public List<MenuNode> getMenuPower(Integer id) {
        if (id != null) {
            List<Integer> list = menuDao.selectIdListByUserId(id);
            List<MenuNode> menuNodes = menuDao.selectList();
            for (MenuNode menuNode : menuNodes) {
                List<MenuNode> child = menuNode.getChild();
                for (MenuNode node : child) {
                    node.setChoose("0");
                    for (Integer menuId : list) {
                        if (node.getId().equals(menuId)) {
                            node.setChoose("1");
                        }
                    }
                }
            }
            return menuNodes;
        }
        return null;
    }

    /**
     * 根据用户id及菜单id进行菜单权限分配
     *
     * @param menuIds
     * @param userId
     * @return
     */
    @Override
    public JsonResult userCorrelationMenu(Integer[] menuIds, Integer userId) {
        try {
            if (userId != null) {
                userDao.deleteMenuByUserId(userId);
                if (menuIds != null && menuIds.length > 0) {
                    //添加父级节点
                    List<Integer> prentId = menuDao.findPrentId();
                    for (Integer integer : prentId) {
                        userDao.addUserMenu(userId, integer);
                    }
                    //添加前端传入的节点
                    for (Integer menuId : menuIds) {
                        userDao.addUserMenu(userId, menuId);
                    }
                }
                return JsonResult.success("修改成功");
            }
            return JsonResult.error("修改失败");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("修改失败");
        }
    }

    @Override
    public List<Integer> getPermissionPower(String id) {
        if (StringUtils.isNotEmpty(id)) {
            List<Integer> list = userDao.selectPermissionIdByUserId(id);
            return list;
        }
        return null;
    }

    @Override
    public JsonResult userCorrelationPermission(String[] permissionIds, String userId) {
        if (StringUtils.isNotEmpty(userId)) {
            userDao.delPermissionByUserId(Integer.parseInt(userId));
            //根据userId查询用户
            UserInfo userInfo = userDao.findByUserId(userId);
            //获得初始权限
            Integer userLevel = userInfo.getUserLevel();
            if (userLevel == 1) {
                userDao.addPermissionUser(userId, "1");
            } else if (userLevel == 2) {
                userDao.addPermissionUser(userId, "2");
            } else if (userLevel == 3) {
                userDao.addPermissionUser(userId, "3");
            }
            if (permissionIds != null && permissionIds.length > 0) {

                for (String permissionId : permissionIds) {
                    userDao.addPermissionUser(userId, permissionId);
                }
            }
            return JsonResult.success("修改成功");
        }
        return JsonResult.error();
    }

    @Override
    public List<Project> getSectionPower(String id) {
        if (StringUtils.isNotEmpty(id)) {
            List<Section> list = sectionDao.findByUserId(id);
            List<Integer> ids = new ArrayList<>();
            for (Section section : list) {
                Integer sectionId = section.getId();
                ids.add(sectionId);
            }
            List<Project> projectList = projectDao.selectAll();
            for (Project project : projectList) {
                List<Section> sectionList = project.getSectionList();
                for (Section section : sectionList) {
                    section.setChoose(0);
                    for (Integer sectionId : ids) {
                        if (section.getId().equals(sectionId)) {
                            section.setChoose(1);
                        }
                    }
                }
            }
            return projectList;
        }
        return null;

    }

    @Override
    public JsonResult userCorrelationSection(String[] sectionIds, String userId) {
        if (StringUtils.isNotEmpty(userId)) {
            //根据userId删除标段关联
            userDao.delUserSectionByUserId(userId);
            if (sectionIds != null && sectionIds.length > 0) {
                for (String sectionId : sectionIds) {
                    userDao.addUserSection(userId, sectionId);
                }
            }
            return JsonResult.success("修改成功");
        }
        return JsonResult.error();
    }


}
